package tripx.db;

import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

import tripx.db.system.Logger;

/**
 * A connector which connects to database, this may be modified when you change
 * your database product.
 * 
 * @author zhb
 * 
 */
public class DbConnector {

	private String userName;

	private String host;

	private String port;

	private String password;

	private String dbName;

	private String protocal;

	private String driverClass;

	private Connection connection;

	public DbConnector(String userName, String host, String port,
			String password, String dbName, String protocal, String driverClass) {
		this.userName = userName;
		this.host = host;
		this.port = port;
		this.password = password;
		this.dbName = dbName;
		this.protocal = protocal;
		this.driverClass = driverClass;
	}

	/**
	 * connect to the database.
	 */
	public void openConnection() {
		/* load the database driver */
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			Logger.getInstance().err("Driver not found..");
		}
		/* initialize the connection */
		try {
			connection = (Connection) DriverManager.getConnection(protocal
					+ host + ":" + port + "/" + dbName, userName, password);
		} catch (SQLException e) {
			Logger.getInstance().err("Connection Error..");
		}
	}

	/**
	 * get the <code><b>Connection</b></code> instance to operate the database,
	 * you should always call {@link #openConnection()} first, otherwise
	 * <code><b>null</code></b> will be returned.
	 * 
	 * @return an instance of the database Connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * close the connection to release the resources.
	 */
	public void closeConnection() {
		try {
			connection.close();
		} catch (SQLException e) {
			Logger.getInstance().err("Close Error..");
		}
	}
}
